using JamesFan.FetchAreaCodes.Cli;
using MySql.Data.MySqlClient;
using SqlSugar;
using Viyi.Strings.Extensions;
using Viyi.Util.Extensions;

namespace JamesFan.FetchAreaCodes.Repository.MySql;

internal class MySqlRepository : AbstractRepository {
    public static string BuildConnectionString(DbConfiguration options) {
        return new MySqlConnectionStringBuilder() {
            Database = options.Database,
            Server = options.Server,
            Port = options.Port,
            UserID = options.Username,
            Password = options.Password,
            CharacterSet = options.Charset,
        }.ToString();
    }

    public static ConnectionConfig CreateConfig(string connString) {
        var builder = new MySqlConnectionStringBuilder(connString).Also(builder => {
            builder.CharacterSet = builder.CharacterSet.EmptyAs("utf8mb4");
            if (builder.Port == 0) { builder.Port = 3306; }
        });

        return new ConnectionConfig {
            DbType = DbType.MySql,
            ConnectionString = builder.ToString(),
        };
    }

    public MySqlRepository(string connString) : base(CreateConfig(connString)) { }
}
